/*
 * @lc app=leetcode id=463 lang=cpp
 *
 * [463] Island Perimeter
 */

// @lc code=start
#include <vector>
class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        int ans = 0;
        std::vector<std::pair<int,int>> dirs= {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 1) {
                    for (auto dir : dirs) {
                        int idx = i + dir.first;
                        int idy = j + dir.second;
                        if (idx < 0 || idy < 0 || idx >= m || idy >= n) {
                            ans++;
                        } else if (idx >= 0 && idx < m  && idy >= 0 && idy < n && grid[idx][idy] == 0) {
                            ans++;
                        }
                    }
                    
                }
            }
        }
        return ans;
    }
};
// @lc code=end

